#!/usr/bin/python
# This shows a service of an MQTT subscriber.
# Copyright (c) 2010-2015, By openthings@163.com.

import sys
import datetime
import threading
import socket, sys

#======================================================        
#MQTT Initialize.--------------------------------------
try:
    import paho.mqtt.client as mqtt
except ImportError:
    print("MQTT client not find. Please install as follow:")
    print("git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git")
    print("cd org.eclipse.paho.mqtt.python")
    print("sudo python setup.py install")

IS_RUN = 1
global gpsfile
global gpsfilename
gpsfilename = "gpslog_BD.txt"

global strMqttBroker
global strMqttChannel
strMqttBroker = "112.124.67.178"
strMqttChannel1 = "/inode/gps/m8n-01/adj"
strMqttChannel2 = "/inode/gps/m8n-01/raw"

#======================================================
def on_connect(mqttc, obj, rc):
    print("OnConnect, rc: "+str(rc))

def on_disconnect(mqttc, obj, rc):
    global strMqttBroker
    global strMqttChannel
    print("OnDisConnect, rc: "+str(rc))
    start()

def on_publish(mqttc, obj, mid):
    print("OnPublish, mid: "+str(mid))

def on_subscribe(mqttc, obj, mid, granted_qos):
    print("Subscribed: "+str(mid)+" "+str(granted_qos))

def on_log(mqttc, obj, level, string):
    print("Log:"+string)

def on_message(mqttc, obj, msg):
    curtime = datetime.datetime.now()
    strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
    print(strcurtime + ": " + msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
    #on_exec(str(msg.payload))

def on_exec(strcmd):
    print "Exec:",strcmd
    strExec = strcmd

#============================================    
def service_start():
    mqttc = mqtt.Client("inode-gps-transmiter")
    mqttc.on_message = on_message
    mqttc.on_connect = on_connect
    mqttc.on_disconnect = on_disconnect
    mqttc.on_publish = on_publish
    mqttc.on_subscribe = on_subscribe
    mqttc.on_log = on_log

    mqttc.connect(strMqttBroker, 1883, 60)
    mqttc.subscribe(strMqttChannel1, 0)
    mqttc.subscribe(strMqttChannel2, 0)
    mqttc.loop_forever()

def worker_start():
    t_worker = threading.Thread(target=service_start,args=())
    t_worker.setDaemon(True)
    t_worker.start()

#============================================
def exeCMD(xcmd):
    print(">>CMD:",xcmd)

def waitinput():
    global gpsfile
    while True: 
        xcmd = raw_input('') 
        if (xcmd.upper()=="EXIT"):
            IS_RUN = 0
            #tcpClientSock.close()
            print "[ inodeService receiver ] exited."
            gpsfile.close()
            exit()
        #exeCMD(xcmd)

#=====================================================
if __name__ == '__main__': 
    try:
        gpsfile = open(gpsfilename,'w')
        worker_start()
        waitinput()
    except Exception, e:
        print("========ERROR PARSE DATA===================")
        print(e)
        print("===========================================")
    finally:
        worker_start()    
  